package sg.edu.nus.iss.billing.localization;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import sg.edu.nus.iss.billing.exception.UnrecoverableError;

public class MessageKeyManager {

	private static String globalLocale = "EN";
	public static final String EN_LOCALE = "EN";
	public static final String PT_LOCALE = "PT";
	public static final String ID_LOCALE = "ID";
	private static File messageKeyPropsFile;
	private static Properties props;
	static {
		reload();
	}

	public static void setLocale(String locale) {
		globalLocale = locale;
	}

	public static void reload() {
		if (globalLocale.equals("EN")) {
			messageKeyPropsFile = new File(
					"resource/applicationResources_en.properties");
		} else if (globalLocale.equals("PT")) {
			messageKeyPropsFile = new File(
					"resource/applicationResources_pt.properties");
		} else if (globalLocale.equals("ID")) {
			messageKeyPropsFile = new File(
					"resource/applicationResources_id.properties");
		}
		try {
			props = new Properties();
			props.load(new FileInputStream(messageKeyPropsFile));
		} catch (FileNotFoundException e) {
			throw new UnrecoverableError(e);
		} catch (IOException e) {
			throw new UnrecoverableError(e);
		}
	}

	public static String getMessage(String key, String... replacements) {
		String result = props.getProperty(key, key);
		if (replacements != null && replacements.length > 0) {
			for (int i = 0; i < replacements.length; i++) {
				String replaceKey = "{" + i + "}";
				result = result.replace(replaceKey, replacements[i]);
			}
		}
		return result;
	}
	
}
